package com.tuanzi.loan.web.bean.credithousekeeper;

import com.base.common.http.HttpClientUtil;
import com.base.common.http.model.FormData;
import com.base.common.http.model.HttpResult;
import com.base.common.http.model.PostData;
import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.starbaba.model.network.Phead;
import com.starbaba.model.user.UserUtil;
import com.starbaba.model.utils.ZipUtil;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.LoginUser;
import com.tuanzi.loan.business.entity.accountTool.LoanCompensOrderOperateLog;
import com.tuanzi.loan.business.repository.accountTool.CompensOrderLogRepository;
import com.tuanzi.loan.business.service.credithousekeeper.CreditCompensatoryOrderService;
import com.tuanzi.loan.vo.request.credithousekeeper.CreditCompensatoryOrderRequest;
import com.tuanzi.loan.vo.response.credithousekeeper.CreditCompensatoryOrderResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.credithousekeeper.CreditCompensatoryOrderLazyDataModel;
import com.tuanzi.server.loan_base.constant.CardCompensationOrderStatus;
import com.tuanzi.server.loan_base.util.DateUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.DAICHANGTYPE;

/**
 * @Description: 信用卡代偿订单后台bean
 * @Author: xionghao
 * @CreateDate: 2018-07-18
 */
@Data
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class CreditCompensatoryOrderListBean extends JSFListingBean<CreditCompensatoryOrderRequest, CreditCompensatoryOrderResponse> {

    private static final long serialVersionUID = 520358946858552202L;

    @Value("${compensation.cancel-order.url}")
    private String url;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private CompensOrderLogRepository orderLogRepository;

    @Autowired
    private CreditCompensatoryOrderService creditCompensatoryOrderService;

    @PostConstruct
    public void init() {
        initLazyDataModel();
    }

    private void initLazyDataModel() {
        $ = new CreditCompensatoryOrderRequest();
        try {
            $.setStartDate(sdf.parse(DateUtils.getCurrentDate()));
            $.setEndDate(sdf.parse(DateUtils.getCurrentDate()));
        } catch (ParseException e) {
           LogService.error("日期类型转换异常",e);
        }
        lazyDataModel = new CreditCompensatoryOrderLazyDataModel($);
    }

    public void cancelOrder(String trans_id) {

//        String URL = "http://tuanzidai.cn" + "/loan_account_tool/common?funid=91&rd=" + System.currentTimeMillis();
        String URL = this.url + System.currentTimeMillis();

        Phead phead = new Phead();
        phead.setAccess_token(UserUtil.getToken(8619106L));
        JsonObject requestJson = new JsonObject();
        JsonElement pheadJson = new Gson().toJsonTree(phead);
        requestJson.add("phead", pheadJson);
        requestJson.addProperty("activity_id", "260");
        requestJson.addProperty("src_project", "loan_account_tool");
        requestJson.addProperty("trans_id", trans_id);

        FormData formdata = new FormData();
        formdata.addParam("handle", "0");
        formdata.addParam("data", requestJson.toString());
        formdata.addParam("shandle", "1");
        PostData postData = new PostData(formdata);

        JsonObject formJson = new JsonObject();
        formJson.addProperty("handle", "0");
        formJson.addProperty("shandle", "1");
        formJson.add("data", requestJson);
        System.out.println(formJson);

        HttpResult httpResult = null;
        JsonElement result_status = null;
        try {
            httpResult = HttpClientUtil.post(URL, postData);
            String responsedata = ZipUtil.unCompressData(httpResult.getData());
            JsonParser parser = new JsonParser();
            JsonObject responseJson = parser.parse(responsedata).getAsJsonObject();
            result_status = responseJson.get("result_status");
        } catch (Exception e) {
            LogService.error("取消信用卡代偿订单失败:" + e.getMessage());
        }
        if (result_status != null && "1".equals(result_status.getAsString())) {
            addSuccessfullyMessage();
            LoginUser loginUser = CurrentUser.get();
            String account = loginUser.getAccount();
            String operator = loginUser.getName();
            LoanCompensOrderOperateLog log = new LoanCompensOrderOperateLog();
            log.setAccount(account);
            log.setUserName(operator);
            log.setCtime(new Date());
            log.setTransId(trans_id);
            orderLogRepository.save(log);
        } else {
            addFiledMessage("取消失败");
        }


    }


    //订单状态：待确认、处理中、成功、失败、中止、异常
    public String traslationOrderStatus(Integer status) {
        if (status != null || !"".equals(status)) {
            switch (status) {
                case CardCompensationOrderStatus.ALLIN_TO_BE_CONFIRM:
                    return "待确认";
                case CardCompensationOrderStatus.ALLIN_PROCESSING:
                    return "处理中";
                case CardCompensationOrderStatus.ALLIN_SUCCESS:
                    return "成功";
                case CardCompensationOrderStatus.ALLIN_FAIL:
                    return "失败";
                case CardCompensationOrderStatus.ALLIN_PAUSE:
                    return "中止";
                case CardCompensationOrderStatus.ALLIN_EXCEPTION:
                    return "异常";
                default:
                    return "无此状态";
            }
        } else {
            return "未传入状态";
        }
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(DAICHANGTYPE);
    }
}
